package com.example.contentresolvertest

import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.widget.ArrayAdapter
import android.widget.Button
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.contentresolvertest.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {

    private val contentList = ArrayList<String>()
    private lateinit var adapter:ArrayAdapter<String>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        val binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, contentList)
        binding.listView.adapter = adapter
        binding.button.setOnClickListener{
            readContent()
        }
    }

    private fun readContent() {
        contentList.add("1")
        contentList.add("2")
        contentList.add("3")
        adapter.notifyDataSetChanged()

//        val uri = Uri.parse("content://com.example.contentprovider.provider/book")
//        contentResolver.query(uri,null,null,null,null)?.apply {
//            while(moveToNext()){
//                val name = getString(getColumnIndex("name"))
//                val price = getDouble(getColumnIndex("price"))
//                Log.d(javaClass.simpleName, "onCreate: $name,$price")
//            }
//            close()
//        }

        val uri = Uri.parse("content://com.example.contentprovider.provider/book")
        contentResolver.query(uri, null,null,null,null)?.apply {
            while(moveToNext()){
                val name = getString(getColumnIndex("name"))
                val price  = getDouble(getColumnIndex("price"))
                contentList.add("$name/n$price")
            }
            adapter.notifyDataSetChanged()
            close()
        }
    }
}